package com.ceair.flight.refund.service.notification.impl;

import com.alibaba.fastjson.JSON;
import com.ceair.flight.refund.location.dao.IOrderDao;
import com.ceair.flight.refund.location.model.OrderDO;
import com.ceair.flight.refund.service.notification.IRefundFailNotification;
import com.ceair.muservice.basicdata.dto.channel.ChannelManageDto;
import com.ceair.muservice.basicdata.feign.util.ChannelUtil;
import com.ceair.muservice.common.constant.QueueName;
import com.ceair.muservice.common.dto.queue.MailAndSMSMessage;
import com.ceair.muservice.common.enums.message.TemplateNameEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 退票失败发送通知
 *
 * @author: chenglongyi
 **/
@Service
public class RefundFailNotification implements IRefundFailNotification {
    private static final Logger logger = LoggerFactory.getLogger(RefundFailNotification.class);

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private IOrderDao orderDao;

    /**
     * 退票失败发送邮件
     *
     * @param orderNo 订单号
     */
    @Override
    public void sendRefundFailMail(String orderNo) {
        logger.info("开始发送退票失败邮件，orderNo:" + orderNo);
        OrderDO orderDO = orderDao.queryOrder(orderNo);
        if (orderDO == null) {
            logger.info("订单号不存在！orderNO:" + orderNo);
            throw new RuntimeException("订单号不存在！orderNo:" + orderNo);
        }
        String channel = orderDO.getChannel();
        ChannelManageDto channelManageDto = ChannelUtil.findChannelByChannelCode(channel);
        String site = channelManageDto.getLanguageCode();
        String[] siteSplit = site.split("_");
        String language = siteSplit[0];
        String country = siteSplit[siteSplit.length - 1];
        /**
         * 使用通用模板
         */
        MailAndSMSMessage mailMessage = new MailAndSMSMessage();
        mailMessage.setChannel(channel);
        mailMessage.setCountry(country);
        mailMessage.setLanguage(language);
        mailMessage.setMsgTP("MAIL");
        mailMessage.setServerTy(TemplateNameEnum.REFFAIL_MAIL.getCode());

        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("site", language);
        mailMap.put("receiver", orderDO.getContactEmail());
        mailMap.put("ordNo", orderNo);
        mailMessage.setMap(mailMap);
        String messageStr = JSON.toJSONString(mailMessage);
        amqpTemplate.convertAndSend(QueueName.MAIL_AND_SMS, messageStr);
        logger.info("发送邮件结束!mailMessage:\n" + messageStr);
    }
}
